from django.contrib.auth import login, logout, authenticate
from django.views.decorators.http import require_POST
from django.http import HttpResponse
from django.shortcuts import reverse, redirect
from django.core.cache import cache
from django.contrib.auth import get_user_model
from io import BytesIO
from .forms import LoginForm, RegisterForm
from utils.captcha.xfzcaptcha import Captcha
from utils import restful
from utils.smssender import juhesms

User = get_user_model()


# 用户登录
@require_POST
def login_view(request):
    forms = LoginForm(request.POST)
    if forms.is_valid():
        telephone = forms.cleaned_data.get('telephone')
        password = forms.cleaned_data.get('password')
        remember = forms.cleaned_data.get('remember')
        user = authenticate(request, username=telephone, password=password)
        if user:
            if user.is_active:
                login(request, user)
                if remember:
                    request.session.set_expiry(None)
                else:
                    request.session.set_expiry(0)
                return restful.ok()
            else:
                return restful.unauth(message='账号已被冻结！')
        else:
            return restful.params_error(message='手机号或者密码错误！')
    else:
        errors = forms.get_errors()
        return restful.params_error(message=errors)


# 用户注销
def logout_view(request):
    logout(request)
    return redirect(reverse('index'))


# 用户注册
@require_POST
def register_view(request):
    forms = RegisterForm(request.POST)
    if forms.is_valid():
        telephone = forms.cleaned_data.get('telephone')
        username = forms.cleaned_data.get('username')
        password = forms.cleaned_data.get('password1')
        user = User.objects.create_user(telephone=telephone, username=username, password=password)
        login(request, user)
        return restful.ok()
    else:
        return restful.params_error(message=forms.get_errors())


# 图形验证码
def img_captcha(request):
    text, image = Captcha.gene_code()
    # BytesIO相当于一个管道，用来存储图片的流数据
    out = BytesIO()
    # 调用image的save方法，将这个image对象保存到BytesIO中
    image.save(out, 'png')
    # 将BytesIO的文件指针移动到最开始的位置
    out.seek(0)

    response = HttpResponse(content_type='image/png')
    # 从BytesIO中读取出image数据，并存到response中
    response.write(out.read())
    response['Content-length'] = out.tell()
    print(text)

    cache.set(text.lower(), text.lower(), 5*60)
    print(cache.get(text.lower()))

    return response


# 短信验证码
def sms_captcha(request):
    telephone = request.GET.get('telephone')
    code = Captcha.gene_text()
    cache.set(telephone, code, 5*60)
    print(code)
    # result = juhesms.sms_captcha(telephone, code)
    if code:
        return restful.ok()
    else:
        return restful.params_error(message="短信验证码发送失败！")


# def cache_test(request):
#     cache.set('tang', 'wenjie', 60)
#     result = cache.get('tang')
#     print(result)
#     return HttpResponse('success')
